package com.atguigu.eduservice.controller.admin;


import com.atguigu.commonutils.R;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;


/**
 * @author alan
 */
@RestController
@RequestMapping("/eduService/subject")
@CrossOrigin
public class EduSubjectController {

    @Resource
    private EduSubjectService eduSubjectService;

    @ApiOperation(value = "Excel批量导入")
    @PostMapping
    public R addSubject(MultipartFile file) {
        eduSubjectService.importSubjectData(file, eduSubjectService);
        //判断返回集合是否为空
        return R.ok();
    }

    @ApiOperation(value = "获取所有的分类")
    @PostMapping("/listSubject")
    public R listSubject() {
        List<EduSubject> list = eduSubjectService.list(Wrappers.<EduSubject>lambdaQuery()
                .eq(EduSubject::getParentId, "0").orderByAsc(EduSubject::getSort));
        for (EduSubject eduSubject : list) {
            List<EduSubject> result = eduSubjectService.list(Wrappers.<EduSubject>lambdaQuery()
                    .eq(EduSubject::getParentId, eduSubject.getId()).orderByAsc(EduSubject::getSort));
            eduSubject.setChildren(result);
        }
        return R.ok().data("list", list);
    }

    @ApiOperation(value = "删除")
    @PostMapping("/del/{id}")
    public R delete(@PathVariable("id") String id) {
        if (eduSubjectService.deleteById(id)) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @ApiOperation(value = "删除全部")
    @PostMapping("/delAll")
    public R delAll() {
        eduSubjectService.remove(null);
        return R.ok();
    }

    @ApiOperation(value = "添加")
    @PostMapping("/saveChild")
    public R saveChild(@RequestBody EduSubject eduSubject) {
        if (eduSubjectService.save(eduSubject)) {
            return R.ok();
        }
        return R.error();
    }

    @ApiOperation(value = "修改")
    @PostMapping("/update")
    public R update(@RequestBody EduSubject eduSubject) {
        if (eduSubjectService.updateById(eduSubject)) {
            return R.ok();
        }
        return R.error();
    }
}

